import { Card, message, Row, Col, Space } from 'antd';
import { history } from 'umi';
import ProForm, {
  ProFormDatePicker,
  ProFormUploadButton,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-form';
import { useRequest } from 'umi';
import type { FC } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import {
  fakeSubmit,
  queryArticleDetail,
  updateArticle,
  fakeSubmitNotice,
  queryDeptList,
  queryArticleDepts,
  updateArticleDeptIds,
} from './service';
import RichText from '@/components/RichText';

const BasicForm: FC<Record<string, any>> = () => {
  const { run } = useRequest(fakeSubmit, {
    manual: true,
    onSuccess: () => {
      message.success('提交成功');
      history.push('/article/article-list');
    },
  });

  // const { data, loading } = useRequest(() => {
  //   if (history.location.query.id) {
  //     return queryArticleDetail(history.location.query);
  //   }
  // });

  const onFinish = async (values: Record<string, any>) => {
    // let diseaseIds = [];
    // let diseaseTags = '';
    console.log('values', values);
    if (values.upload.length > 0) {
      if (values.upload[0].url) {
        let arr = values.upload[0].url.split('http://oss.yizuoyiyou.com.cn');
        values.cover = arr[1];
      }
      if (values.upload[0].response) {
        values.cover = values.upload[0].response.data.url;
      }
    }
    values.channel = '130200';

    if (history.location.query.id) {
      values.id = history.location.query.id;
      try {
        const response = await updateArticle(values);
        if (response.code == 200) {
          let params = {
            id: history.location.query.scienceId,
          };
          if (values.deptIds) {
            params.deptIds = ',' + values.deptIds.join(',') + ',';
            const res = await updateArticleDeptIds(params);
            if (res.code == 200) {
              message.success('修改成功');
              history.push('/publish/science');
            } else {
              message.error('修改失败!');
            }
          } else {
            message.success('修改成功');
            history.push('/publish/science');
          }
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        message.error(error);
        console.log(error);
      }
    } else {
      const response = await fakeSubmit(values);
      if (response.code == 200) {
        let params = {
          articleId: response.data,
          hospitalId: sessionStorage.getItem(`hosiptaAuthlId`),
          articleType: 2,
          articleTitle: values.title,
        };
        if (values.deptIds) {
          params.deptIds = ',' + values.deptIds.join(',') + ',';
        }
        const res = await fakeSubmitNotice(params);
        if (res.code == 200) {
          message.success('发布成功');
          history.push('/publish/science');
        } else {
          message.error('发布失败!');
        }
      } else {
        message.error('发布失败!');
      }
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          hideRequiredMark
          style={{ margin: 'auto', marginTop: 8 }}
          name="basic"
          layout="horizontal"
          // initialValues={data}
          onFinish={onFinish}
          {...formItemLayout}
          request={async () => {
            if (history.location.query.id) {
              const res = await queryArticleDetail(history.location.query);
              if (res.code == 200) {
                let data = res.data;
                if (data.cover) {
                  let upload = [
                    {
                      uid: '1',
                      name: 'icon',
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + data.cover,
                    },
                  ];
                  data.upload = upload;
                }
                data.addUserType = data.addUserType + '';
                data.channel = data.channel + '';
                const response = await queryArticleDepts({ id: history.location.query.scienceId });

                if (response.code == 200) {
                  console.log('response', response);
                  if (response.data != null) {
                    let deptIds = [];
                    for (var i = 0; i < response.data.length; i++) {
                      deptIds.push(response.data[i].id);
                    }
                    data.deptIds = deptIds;
                  }
                }
                console.log('data------', data);
                return data;
              }
            } else {
              return {};
            }
          }}
          submitter={{
            render: (props, doms) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              );
            },
          }}
        >
          <ProFormText
            width="md"
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入标题',
              },
            ]}
            placeholder="请输入文章标题"
          />
          <ProFormText
            width="md"
            label="副标题"
            name="subTitle"
            rules={[
              {
                required: true,
                message: '请输入副标题',
              },
            ]}
            placeholder="请输入文章副标题"
          />
          {/* <ProFormSelect
            width="md"
            name="diseases"
            label="疾病标签"
            showSearch
            fieldProps={{
              mode: 'multiple',
              labelInValue: true,
            }}
            request={async () => {
              return queryDiseaseTags().then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.name,
                    value: item.id,
                  };
                });
              });
            }}
          /> */}
          <ProForm.Item label="正文内容" name="content">
            <RichText />
          </ProForm.Item>
          <ProFormUploadButton
            name="upload"
            label="封面"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
            rules={[
              {
                required: true,
                message: '请上传封面',
              },
            ]}
          />
          <ProFormSelect
            width="md"
            name="deptIds"
            label="关联科室（选填）"
            showSearch
            fieldProps={{
              mode: 'multiple',
            }}
            request={async () => {
              const params = { hospitalId: sessionStorage.getItem(`hosiptaAuthlId`), level: 2 };
              return queryDeptList(params).then(({ data }) => {
                return data.map((item) => {
                  return {
                    label: item.name,
                    value: item.id,
                  };
                });
              });
            }}
          />
          {/* 
           <ProFormRadio.Group
            options={[
              {
                value: '0',
                label: '用户',
              },
              {
                value: '1',
                label: '医生',
              },
              {
                value: '2',
                label: '系统',
              },
            ]}
            label="创作人"
            name="addUserType"
          /> */}
          {/* <ProFormText
            width="md"
            label="用户id"
            name="addUserId"
            rules={[
              {
                required: true,
                message: '请输入用户id',
              },
            ]}
            placeholder="请输入用户id"
          /> 
          <ProFormDatePicker width="md" name="publishTime" label="创作日期" />*/}
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
